<template>
  <div class="rtmp-config">
    <a-form :model="formState" layout="vertical" @finish="handleSubmit">
      <a-card :title="$t('rtmp.title')" :bordered="false">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item :label="$t('rtmp.enable')" name="enabled">
              <a-switch v-model:checked="formState.enabled" />
            </a-form-item>
          </a-col>
        </a-row>

        <div class="sinks-header">
          <a-space>
            <span>{{ $t('rtmp.destinations') }}</span>
            <a-button type="dashed" size="small" @click="addSink" :disabled="formState.sinks.length >= maxSinks">
              {{ $t('rtmp.add') }}
            </a-button>
          </a-space>
          <div class="help-text">{{ $t('rtmp.max', { count: maxSinks }) }}</div>
        </div>

        <div v-for="(sink, index) in formState.sinks" :key="index" class="sink-config">
          <div class="sink-header">
            <h4>{{ $t('rtmp.destination', { index: index + 1 }) }}</h4>
            <a-space>
              <a-form-item :label="$t('rtmp.enabled')" :name="['sinks', index, 'enabled']" style="margin-bottom: 0;">
                <a-switch v-model:checked="sink.enabled" />
              </a-form-item>
              <a-button type="text" danger size="small" @click="removeSink(index)" v-if="formState.sinks.length > 1">
                {{ $t('common.delete') || '删除' }}
              </a-button>
            </a-space>
          </div>
          <div class="sink-status">
            <span>{{ $t('rtmp.status') }}：
              <span :class="['state', sinkStateClass(index)]">{{ sinkStateText(index) }}</span>
            </span>
          </div>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item 
                :label="$t('rtmp.url')" 
                :name="['sinks', index, 'url']"
                :rules="[
                  { required: true, message: '请输入推流URL' },
                  { validator: (r,v) => validateUrlRule(v) }
                ]"
              >
                <a-input v-model:value="sink.url" :placeholder="$t('rtmp.urlPlaceholder')" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label="$t('rtmp.channel')" :name="['sinks', index, 'channel']">
                <a-input-number v-model:value="sink.channel" :min="0" :max="15" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label="$t('rtmp.streamType')" :name="['sinks', index, 'stream_type']">
                <a-input-number v-model:value="sink.stream_type" :min="0" :max="3" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-card>

      <div style="margin-top: 24px">
        <a-space>
          <a-button type="primary" html-type="submit" :loading="loading">{{ $t('rtmp.save') }}</a-button>
          <a-button @click="handleReset">{{ $t('rtmp.reset') }}</a-button>
          <a-button @click="fetchConfig">{{ $t('rtmp.refresh') }}</a-button>
        </a-space>
      </div>
    </a-form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { message } from 'ant-design-vue';
import { getRTMPConfig, setRTMPConfig, validateRtmpUrl } from '@/api/rtmp';

export default defineComponent({
  name: 'RTMPConfig',
  setup() {
    const { t } = useI18n();
    const maxSinks = 4;
    const defaultConfig = {
      enabled: false,
      sinks: [
        { enabled: false, url: '', channel: 0, stream_type: 0 }
      ]
    };

    const formState = reactive(JSON.parse(JSON.stringify(defaultConfig)));
    const loading = ref(false);
    const status = ref({ enabled: false, sinks: [] });

    const addSink = () => {
      if (formState.sinks.length < maxSinks) {
        formState.sinks.push({ enabled: false, url: '', channel: 0, stream_type: 0 });
      }
    };

    const removeSink = (index) => {
      if (formState.sinks.length > 1) {
        formState.sinks.splice(index, 1);
      }
    };

    const sanitizeConfig = (cfg) => {
      // 只保留必要字段，并转换为后端需要的结构
      return {
        enabled: !!cfg.enabled,
        sinks: (cfg.sinks || []).map(s => ({
          enabled: !!s.enabled,
          url: (s.url || '').trim(),
          channel: Number.isFinite(s.channel) ? s.channel : 0,
          stream_type: Number.isFinite(s.stream_type) ? s.stream_type : 0
        }))
      };
    };

    const fetchConfig = async () => {
      loading.value = true;
      try {
        const cfg = await getRTMPConfig();
        const merged = sanitizeConfig({ ...defaultConfig, ...cfg });
        Object.assign(formState, merged);
        // 同步拉取状态
        try {
          status.value = await getRTMPStatus();
        } catch (e) {
          status.value = { enabled: formState.enabled, sinks: formState.sinks.map(s => ({...s, state: 'unknown'})) };
        }
      } catch (err) {
        console.error('加载RTMP配置失败:', err);
        message.error('加载配置失败');
      } finally {
        loading.value = false;
      }
    };

    const validateUrlRule = (value) => {
      if (!value) return Promise.reject('请输入推流URL');
      if (!validateRtmpUrl(value)) return Promise.reject('URL 必须以 rtmp:// 或 rtmps:// 开头');
      return Promise.resolve();
    };

    const handleSubmit = async () => {
      try {
        const cfg = sanitizeConfig(formState);
        // 基本校验
        for (const s of cfg.sinks) {
          if (s.enabled) {
            if (!s.url) throw new Error('启用的目的地必须填写URL');
            if (!validateRtmpUrl(s.url)) throw new Error('URL 必须以 rtmp:// 或 rtmps:// 开头');
          }
        }
        await setRTMPConfig(cfg);
        message.success('RTMP配置已保存');
      } catch (err) {
        console.error('保存RTMP配置失败:', err);
        message.error('保存失败: ' + (err.message || '请重试'));
      }
    };

    const handleReset = () => {
      Object.assign(formState, JSON.parse(JSON.stringify(defaultConfig)));
      message.info('已重置为默认设置');
    };

    onMounted(() => {
      fetchConfig();
    });

    return {
      formState,
      loading,
      maxSinks,
      addSink,
      removeSink,
      fetchConfig,
      handleSubmit,
      handleReset,
      validateUrlRule,
      status,
      sinkStateText: (idx) => {
        const s = status.value?.sinks?.[idx]?.state || 'unknown';
        if (s === 'disabled') return '未启用';
        if (s === 'connected') return '连接正常';
        if (s === 'connecting') return '连接中';
        if (s === 'error') return '错误';
        return '未知';
      },
      sinkStateClass: (idx) => {
        const s = status.value?.sinks?.[idx]?.state || 'unknown';
        return s;
      }
    };
  }
});
</script>

<style scoped>
.rtmp-config {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.help-text {
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.sinks-header {
  margin-top: 8px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sink-config {
  padding: 16px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  margin-bottom: 12px;
  background-color: #fafafa;
}

.sink-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.sink-header h4 {
  margin: 0;
  color: #333;
  font-weight: 500;
}

.sink-status {
  margin-bottom: 8px;
  color: #666;
}
.state {
  margin-left: 6px;
  padding: 1px 8px;
  border-radius: 10px;
  font-size: 12px;
  background: #f0f0f0;
}
.state.connected { background: #f6ffed; color: #389e0d; }
.state.connecting { background: #e6f7ff; color: #096dd9; }
.state.error { background: #fff2f0; color: #cf1322; }
.state.disabled { background: #fafafa; color: #999; }
.state.unknown { background: #fafafa; color: #999; }
</style>
